<?php
/**
 * 商户模块
 */
namespace Common\Model;
class BusinessModel extends BaseModel{

	const PARTNER_TYPE_ALL	= 0;//全部
	const PARTNER_TYPE_YES	= 1;//合作关系
	const PARTNER_TYPE_NO	= 2;//非合作关系

	const SHOW_ORDER_STAR		=1;//星级降序
	const SHOW_ORDER_DISTANCE	=2;//距离升序

	static $instance=null;
	public static function getInstance(){
		if(!self::$instance){
			self::$instance=M('s_restaurant',null,DB_MAIN_CFG);
		}
		return self::$instance;
	}


	static $storeInstance=null;
	public static function getStoreInstance(){
		if(!self::$storeInstance){
			self::$storeInstance=M('s_store',null,DB_MAIN_CFG);
		}
		return self::$storeInstance;
	}

	static $packageInstance=null;
	public static function getPackageInstance(){
		if(!self::$packageInstance){
			self::$packageInstance=M('s_package',null,DB_MAIN_CFG);
		}
		return self::$packageInstance;
	}


	public static function getRestaurantList(){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataSuccess['data']=self::getInstance()->select();
		return $dataSuccess;
	}



	public static function getRestaurantKv(){
		$data = self::getInstance()->getField('id,restaurantName',true);
		return $data;
	}


	public static function getStoreKv($partnerType=self::PARTNER_TYPE_ALL){
		if($partnerType==self::PARTNER_TYPE_ALL) {
			$data = self::getStoreInstance()->getField('id,storeName', true);
		}else{
			$data = self::getStoreInstance()->where("status={$partnerType}")->getField('id,storeName', true);
		}
		return $data;
	}

	/**
	 * 获取经营目录
	 * @return mixed
	 */
	public static function getBusinessItemKv(){
		$data = M('cfg_business_item',null,DB_MAIN_CFG)->getField('id,item',true);
		return $data;
	}




	/**
	 * 从微信同步门店数据
	 * Author: shijy
	 * @return mixed
	 */
	public static function syncStoreWithWeixin(){
		$weixinStore=WeixinStoreModel::get_all_poilist();
		if($weixinStore['status']!=0){
			return $weixinStore;
		}

		$sql="insert into s_store(id,storeName,address,updateTime) values";
		$values=array();
		$now=time();
		foreach ($weixinStore['data'] as $one){
			$values[]="('{$one['poi_id']}','{$one['business_name']}','{$one['address']}',{$now})";
		}
		$sql .=implode(',',$values);
		$sql .=" on duplicate key update id=values(id),updateTime=values(updateTime),address=values(address)";
		if(M('s_store',null,DB_MAIN_CFG)->execute($sql)===false){
			$dataFailure = array('status'=>self::FAILURE,'msg'=>'执行失败');
			return $dataFailure;
		}
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'门店数据已经成功从微信同步到本地');
		return $dataSuccess;
	}


	public static function getStoreListByRestaurantId($restaurantId=0,$partnerType=self::PARTNER_TYPE_ALL){
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		//$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
		$store = M('s_store',null,DB_MAIN_CFG);
		if($restaurantId==0){
			$where='1';
		}else{
			$where='restaurantId=' . $restaurantId;
		}
		switch ($partnerType){
			case self::PARTNER_TYPE_ALL:
				break;
			case self::PARTNER_TYPE_NO:
			case self::PARTNER_TYPE_YES:
				$where.= " and status={$partnerType}";
				break;
		}


		$list = $store
			->field('id,storeName,address')
			->where($where)
			->select();
		$dataSuccess['data']=$list;
		return $dataSuccess;
	}

	/**
	 * 获取门店列表
	 * @param $page
	 * @param $pageSize
	 * @param int $districtId
	 * @param int $tradeAreaId
	 * @param int $status
	 * @param string $sortType 0,默认，1推荐，2就近
	 * @param string $sortType
	 * @return array
	 */
	public static function getStoreList($page,$pageSize,$districtId=0,$tradeAreaId=0,$status=1,$businessItem=0,$sortType=self::SHOW_ORDER_STAR,$lng=0,$lat=0){
		
		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$storeM=self::getStoreInstance();

		$where = '1';
		//行政区
		if($districtId){
			$where .= " AND district={$districtId} ";
		}

		//商圈
		if($tradeAreaId){
			$where .=" AND tradeAreaId={$tradeAreaId}";
		}

		if($status){
			$where .=" AND status={$status}";
		}
		if($businessItem){
			$where .=" and find_in_set({$businessItem},businessItem)";
		}

		$dataSuccess['total'] = $storeM->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = max($page,1);//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset = ($dataSuccess['page']-1)*$pageSize;

		$juli='';
		switch ($sortType){
			case self::SHOW_ORDER_DISTANCE:
				if($lng==0 && $lat==0){
					$order=' star desc';
				}else {
					$juli = ",ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$lat}*PI()/180-latitude*PI()/180)/2),2)+COS({$lat}*PI()/180)*COS(latitude*PI()/180)*POW(SIN(({$lng}*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli";
					$order = " juli asc ";
				}
				break;
			case self::SHOW_ORDER_STAR:
				$order=' star desc';
				if($lng>0 && $lat>0) {
					$juli = ",ROUND(6378.138*2*ASIN(SQRT(POW(SIN(({$lat}*PI()/180-latitude*PI()/180)/2),2)+COS({$lat}*PI()/180)*COS(latitude*PI()/180)*POW(SIN(({$lng}*PI()/180-longitude*PI()/180)/2),2)))*1000) AS juli";
					$order .=',juli asc';
				}
				break;
			default:
				$order=null;
				break;
		}


		$list = $storeM->where($where)->field("id,restaurantId,storeName,summary,listPic,address,star,longitude,latitude {$juli}")
			->limit($offset,$pageSize)
			->order($order)
			->select();

		$dataSuccess['data'] = $list;
		return $dataSuccess;
	}


	public static function getPackageList($page,$pageSize,$restaurantId=0,$storeId=0,$status=0){

		$dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
		$dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

		$packageM=self::getPackageInstance();
		$where ='1';
		if($status){
			$where .=" AND status={$status}";
		}
		if($restaurantId>0){
			$where .=" AND restaurantId={$restaurantId}";
		}
		if($storeId>0){
			$where .=" AND storeId={$storeId}";
		}



		$dataSuccess['total'] = $packageM->where($where)->count();//获取数据总条数
		$dataSuccess['page'] = max($page,1);//返回当前页
		$dataSuccess['totalPage'] = ceil($dataSuccess['total']/$pageSize);//总共页数
		$dataSuccess['nextPage'] = $dataSuccess['page'] >= $dataSuccess['totalPage'] ? 0 : 1;//是有有下一页
		$offset = ($dataSuccess['page']-1)*$pageSize;

		$list = $packageM->where($where)->field('id,title,restaurantId,storeId,listPic,pricePresent,priceOriginal,status,showOrder,addTime,summary,jumpURL')
			->limit($offset,$pageSize)
			->order("showOrder desc")
			->select();
		$dataSuccess['data'] = $list;
		return $dataSuccess;
	}


	/**
	 * @param $storeId
	 */
	public static function getStoreDetail($storeId){
		return self::getStoreInstance()->where("id={$storeId}")->find();
	}

	/**
	 * 检查手机号是否已经存在，
	 * Author: shijy
	 * @param $phone
	 * @param int $id 用户主键
	 * @return bool
	 */
	public static function checkPhoneExist($phone,$id=0){
		if(!$id){
			if(M('s_verification',null,DB_MAIN_CFG)->where("phone like '{$phone}'")->find()){
				return true;
			}
		}else{
			if(M('s_verification',null,DB_MAIN_CFG)->where("id<>{$id} and phone like '{$phone}' ")->find()){
				return true;
			}
		}
		return false;
	}


	/**
	 * 添加|修改核销员
	 * @param $data {id,phone,password,verificationName,role_id,restaurantId,storeId,jobNum,adminId}
	 * @return bool
	 */
	public static function verificationEdit($data){

		$gmUser=array(
			'username'	=>$data['phone'],
			'password'	=>md5($data['password']),
			'real_name'	=>$data['verificationName'],
			'phone'		=>$data['phone'],
			'status'	=>1,
			'role_id'	=>$data['role_id']
		);
		if($data['role_id'] == ROLE_RESTAURANT_ID){
			$gmUser['belong']=$data['restaurantId'];
		}else{
			$gmUser['belong']=$data['storeId'];
		}

		if(strlen($data['password'])>0){
			$gmUser['password']=md5($data['password']);
		}

		if($data['adminId']>0){
			$adminId=M('sp_sys_user',null,DB_GM_CFG)->where('id='.$data['adminId'])->save($gmUser);
		}else{
			$adminId=M('sp_sys_user',null,DB_GM_CFG)->add($gmUser);
		}

		//////////////////////////////////////////////////////////////////////
		$verificationData=array(
			'restaurantId'	=>$data['restaurantId'],
			'storeId'		=>$data['storeId'],
			'jobNum'		=>$data['jobNum'],
			'verificationName'=>$data['verificationName'],
			'phone'			=>$data['phone'],
			'role_id'		=>$data['role_id']
		);

		if (!$data['adminId']){
			$verificationData['adminId']=$adminId;
		}

		if($data['id']>0){
			M('s_verification',null,DB_MAIN_CFG)->where('id='.$data['id'])->save($verificationData);
		}else{
			M('s_verification',null,DB_MAIN_CFG)->add($verificationData);
		}
		return true;
	}


	/**
	 * 删除核销员
	 * @param $verificationId
	 */
	public static function verificationDel($verificationId){
		$adminId=M('s_verification',null,DB_MAIN_CFG)->where('id='.$verificationId)->getField('adminId');
		M('s_verification',null,DB_MAIN_CFG)->where('id='.$verificationId)->delete();
		M('sp_sys_user',null,DB_GM_CFG)->where('id='.$adminId)->delete();
	}

	/**
	 * 根据所属机构及角色类型取核销员
	 * @param $businessId
	 * @param $roleType
	 * @return mixed
	 */
	public static function getVerificationByBelong($businessId,$roleType){
		switch ($roleType){
			case ROLE_TELLER_ID:
				$verification=M('s_verification',null,DB_MAIN_CFG)->where('restaurantId='.$businessId.' and role_id='.$roleType)->select();
				break;
			case ROLE_STORE_ID:
				$verification=M('s_verification',null,DB_MAIN_CFG)->where('storeId='.$businessId.' and role_id='.$roleType)->find();
				break;
			case ROLE_RESTAURANT_ID:
				$verification=M('s_verification',null,DB_MAIN_CFG)->where('restaurantId='.$businessId.' and role_id='.$roleType)->find();
				break;
		}
		return $verification;
	}



	/**
	 * 核销数据月统计
	 * Author:wwl
	 */
	public static function monStatistic(){
		//获取上月起始时间戳和结束时间戳
		$lastMonTime = UtilsModel::getLastMonth();
		//数据对象时间(15号)
		$objTime = STATISTIC_MONTHLY_OBJTIME;
		$cardM = M('card_code',null,DB_MAIN_CFG);
		$data = $cardM
			->where("verificationStoreId > 0 and consumeTime between {$lastMonTime[0]} and {$lastMonTime[1]}")
			->field("restaurantId,storeId,consumeTime,cardTitle,cardId,count(*) as consumeNum,verificationStoreId")
			->group("cardId,verificationStoreId")
			->select();
		$restaurant = array(); $store = array(); $card = array();
		foreach ($data as $key=>$val){
			$restaurant[] = $val['restaurantId'];
			$store[] = $val['verificationStoreId'];
			$card[] = $val['cardId'];
			$data[$key]['addTime'] = $objTime;
			$data[$key]['restaurantName'] = "不限商户";
		}
		if($restaurant){
			$restaurantStr = implode(',',$restaurant);
			$restaurantInfo = M('s_restaurant',null,DB_MAIN_CFG)->where("id IN ({$restaurantStr})")->getField("id,restaurantName",true);
			foreach ($data as $key => $val){
				foreach ($restaurantInfo as $k => $item){
					if($val['restaurantId'] == $k){
						$data[$key]['restaurantName'] = $item;
					}
				}
			}
		}
		if($store){
			$storeStr = implode(',',$store);
			$storeInfo = M('s_store',null,DB_MAIN_CFG)->where("id IN ({$storeStr})")->getField("id,storeName",true);
			foreach ($data as $key => $val){
				foreach ($storeInfo as $k => $item){
					if($val['verificationStoreId'] == $k){
						$data[$key]['verificationStoreName'] = $item;
					}
				}
			}
		}
		if($card){
			$cardStr = implode(',',$card);
			$cardInfo = M('card_base_info',null,DB_MAIN_CFG)->where("id IN ({$cardStr})")->getField("id,type",true);
			foreach ($data as $key => $val){
				foreach ($cardInfo as $k => $item){
					if($val['cardId'] == $k){
						$data[$key]['cardType'] = $item;
					}
				}
			}
		}
		//月统计存入数据
		M('statistic_card_consume_monthly',null,DB_MAIN_CFG)->addAll($data);
	}


	/**
	 * 发送咨询模板消息
	 * @param $openID
	 * @param $storeName
	 * @param $content
	 */
	public static function sendTemplateMsg_Comment($storeId,$content,$openID=null){
		if (is_null($openID)){
			$openID=BUSINESS_COMMENT_ANSWER;//'o9VjL1IeF2CLYVgy8GPX8iWJWZqI';
		}
		$templateId=WECHAT_TEMPLATE_COMMENT_STORE;//'zT3H9O8Y7_8t37MecHyvNsATVgzFn9Zk-u5ji6EWPCE';
		$storeName=self::getStoreInstance()->where('id='.$storeId)->getField('storeName');
		$url='null';
		$templateMsg=array(
			'touser'=>$openID,
			'template_id'=>$templateId,
			'url'=>$url,
			"topcolor"=>"#FF0000",
			'data'=>array(
				"first"=>array(
					"value"=>"你好，有用户咨询商家",
					"color"=>"#173177"
				),
				"keyword1"=>array(
					"value"=>$storeName,
					"color"=>"#173177"
				),
				"keyword2"=>array(
					"value"=>$content,
					"color"=>"#173177"
				),
				"remark"=>array(
					"value"=>"请尽快登陆后台进行回复",
					"color"=>"#173177"
				),

			)
		);
		$content=json_encode($templateMsg);
		WeixinModel::sendTemplateMsg($content);
	}


	/**
	 * 根据用户输入的商户id  随机生成002~999工号
	 */
	public static function createRandomJobNumber($restaurantId){
		$verification = M('s_verification',null,DB_MAIN_CFG);
		//获取该商铺下所有的工号
		$jobNumList = $verification
			->field('jobNum')
			->where('restaurantId=' . $restaurantId )
			->select();
		//生成1000个工号
		$rangeArray = range(2,999);
		foreach($rangeArray as $key => $value){
			$randomArray[] = array('jobNum'=> str_pad(strval($value),3,0,STR_PAD_LEFT));
		}
		//判断是否存在在商铺里存在该工号 返回不存在的工号
		//有待考虑 是否有更有效的查找方法
		foreach($randomArray as $key => $value){
			if(!in_array($value,$jobNumList)){
				$result [] = $value;
			}
		}
		//判断是否有差集，没有差集则不存在该工号
		if(empty($result)){
			return false;
		}
		//返回当前第一个数值
		$jobNum = each($result);
		//返回工号
		return $jobNum['value']['jobNum'];
	}


}